/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_products/gitsolo.htm
 *
 * gitsolo is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.gitsolo.action;

import java.sql.Timestamp;

import org.zhiqim.gitsolo.GitsoloConstants;
import org.zhiqim.gitsolo.dao.GitMemberDao;
import org.zhiqim.gitsolo.dao.GitProjectDao;
import org.zhiqim.gitsolo.dbo.GitMember;
import org.zhiqim.gitsolo.dbo.GitMemberProject;
import org.zhiqim.gitsolo.dbo.GitProject;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.extend.StdSwitchAction;
import org.zhiqim.httpd.validate.ones.IsIntegerValue;
import org.zhiqim.httpd.validate.ones.IsLen;
import org.zhiqim.httpd.validate.ones.IsNotEmpty;
import org.zhiqim.httpd.validate.onex.IsDate;
import org.zhiqim.kernel.annotation.AnTransaction;
import org.zhiqim.kernel.paging.PageResult;
import org.zhiqim.kernel.util.Ids;
import org.zhiqim.kernel.util.Sqls;
import org.zhiqim.manager.ZmrSessionUser;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;
import org.zhiqim.orm.dbo.Updater;

/**
 * 项目工程管理
 *
 * @version v1.0.0 @author huangsufang 2017-9-25 新建与整理
 */
public class ProjectAction extends StdSwitchAction implements GitsoloConstants
{
    @Override
    protected void validateId(HttpRequest request)
    {        
        request.addValidate(new IsNotEmpty("projectId", "请选择一个选项"));
    }

    @Override
    protected void validateForm(HttpRequest request)
    {
        request.addValidate(new IsLen("projectName", "项目工程名称不能为空且不能超过32个字符", 1, 32));
        request.addValidate(new IsIntegerValue("projectStatus", "项目状态不正确", 0, 1));
        request.addValidate(new IsIntegerValue("projectSeq", "项目排序必须是[0, 999999]范围的非负整数", 0, 999999));
        request.addValidate(new IsDate("projectBeginDate", "项目开始时间不能为空且或格式不正确"));
        request.addValidate(new IsDate("projectEndDate", "项目结束时间不能为空且或格式不正确"));
    }

    @Override
    protected void list(HttpRequest request) throws Exception
    {
        request.setResponsePrivateCache();
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        
        int page = request.getParameterInt("page", 1);
        int pageSize = request.getContextAttributeInt("zmr_page_size", 10);
        String projectName = request.getParameter("projectName");

        Selector sel = new Selector();
        sel.addMaybeLike("projectName", projectName);
        sel.addOrderbyAsc("projectSeq");

        if (sessionUser.isAdmin())
        {// 管理员查看所有
            PageResult<GitProject> result = ORM.table().page(GitProject.class, page, pageSize, sel);
            result.addConditionMap(request.getParameterMap());
            request.setAttribute("result", result);
        }
        else
        {
            sel.addMust("operatorCode", sessionUser.getOperatorCode());
            PageResult<GitMemberProject> result = ORM.view().page(GitMemberProject.class, page, pageSize, sel);
            result.addConditionMap(request.getParameterMap());
            request.setAttribute("result", result);
        }
    }

    @Override
    protected void modify(HttpRequest request) throws Exception
    {
        long projectId = request.getParameterLong("projectId");
        GitProject item = ORM.table().item(GitProject.class, projectId);
        if (item == null)
        {
            request.returnHistory("该项目编码不存在，请重新选择");
            return;
        }
        
        request.setAttribute("item", item);
    }

    @Override @AnTransaction
    protected void insert(HttpRequest request) throws Exception
    { 
        long projectId = Ids.longId13();
        String operatorCode = request.getSessionName();
        Timestamp datetime = Sqls.nowTimestamp();

        GitProject project = request.getParameter(GitProject.class);
        project.setProjectId(projectId);
        project.setProjectManager(operatorCode);
        project.setProjectCreated(datetime);
        project.setProjectModified(datetime);
        ORM.table().insert(project);
        
        GitMember member = new GitMember();
        member.setProjectId(projectId);
        member.setOperatorCode(operatorCode);
        member.setMemberType(0);
        ORM.table().insert(member);
        
        GitMemberDao.report(request, projectId, request.getSessionName(), "创建了项目", project.getProjectName());
    }

    @Override
    protected void update(HttpRequest request) throws Exception
    { 
        long projectId = request.getParameterLong("projectId");
        String projectName = request.getParameter("projectName");
        String projectBeginDate = request.getParameter("projectBeginDate");
        String projectEndDate = request.getParameter("projectEndDate");
        int projectStatus = request.getParameterInt("projectStatus");
        int projectSeq = request.getParameterInt("projectSeq");
        String projectDesc = request.getParameter("projectDesc");
        
        Updater updater = new Updater();
        updater.addMust("projectId", projectId);
        updater.addField("projectName", projectName);
        updater.addField("projectStatus", projectStatus);
        updater.addField("projectBeginDate", projectBeginDate);
        updater.addField("projectEndDate", projectEndDate);
        updater.addField("projectSeq", projectSeq);
        updater.addField("projectDesc", projectDesc);
        updater.addField("projectModified", Sqls.nowTimestamp());
        ORM.table().update(GitProject.class, updater);
        
        GitMemberDao.report(request, projectId, request.getSessionName(), "修改了项目", projectName);
    }

    @Override @AnTransaction
    protected void delete(HttpRequest request) throws Exception
    {
        long projectId = request.getParameterLong("projectId");
        GitProject project = ORM.table().item(GitProject.class, projectId);
        if (project == null)
        {
            request.returnHistory("该项目不存在，请重新选择");
            return;
        }

        ORM.table().delete(GitProject.class, projectId);
        ORM.table().delete(GitMember.class, new Selector("projectId", projectId));
        
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        if (projectId == sessionUser.getOperatorParamLong(GIT_PROJECT_ID_KEY))
        {//当前操作员默认活动的工程被删除，重新选择默认项目
            GitProjectDao.doActiveProject(request, sessionUser);
        }
        
        GitMemberDao.report(request, projectId, request.getSessionName(), "删除了项目", project.getProjectName());
    }
}
